﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Common.Lists;
using DNNToolkit.Modules.Glossary.Components;
using DotNetNuke.Common;
using DotNetNuke.Security;

namespace DNNToolkit.Modules.Glossary
{
    /// <summary>
    /// The ViewGlossary class displays the content.
    /// </summary>
    public partial class ViewGlossary : PortalModuleBase, IActionable
    {
        #region Private Members

        private string headerTemplate;


        /// <summary>
        /// Gets the header template.
        /// </summary>
        /// <value>The header template.</value>
        private string HeaderTemplate
        {
            get
            {
                if (headerTemplate == null)
                {
                    if (!string.IsNullOrEmpty((string)Settings["headertemplate"]))
                        headerTemplate = (string)Settings["headertemplate"];
                    else
                        headerTemplate = Localization.GetString("HeaderTemplate.Text", LocalResourceFile);
                }
                return headerTemplate;
            }
        }

        private string footerTemplate;
        /// <summary>
        /// Gets the footer template.
        /// </summary>
        /// <value>The footer template.</value>
        private string FooterTemplate
        {
            get
            {
                if (string.IsNullOrEmpty(footerTemplate))
                {
                    if (!string.IsNullOrEmpty((string)Settings["footertemplate"]))
                        footerTemplate = (string)Settings["footertemplate"];
                    else
                        footerTemplate = Localization.GetString("FooterTemplate.Text", LocalResourceFile);
                }
                return footerTemplate;
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Populates the template.
        /// </summary>
        private void PopulateTemplate()
        {
            // set header template
            Label headerTemplateLabel = new Label();
            headerTemplateLabel.Text = HeaderTemplate;
            mHeaderSettingPlaceHolder.Controls.Clear();
            mHeaderSettingPlaceHolder.Controls.Add(headerTemplateLabel);

            // set footer template
            Label footerTemplateLabel = new Label();
            footerTemplateLabel.Text = FooterTemplate;
            mFooterSettingPlaceHolder.Controls.Clear();
            mFooterSettingPlaceHolder.Controls.Add(footerTemplateLabel);
        }

        private void PopulateCategoryCombo()
        {
            GlossaryController gController = new GlossaryController();
            var listCategory = gController.ListGlossaryCategoryDefinition();
            mCategoryDropDownList.Items.Add(new ListItem(Localization.GetString("AllCategory.Text", this.LocalResourceFile), "0"));
            foreach (var item in listCategory)
            {
                mCategoryDropDownList.Items.Add(new ListItem(item.CategoryName,item.GlossaryCategoryDefinitionID.ToString()));
            }
        }

        private void PopulateCategoryMenu()
        {
            GlossaryController gController = new GlossaryController();
            mCategoryList.DataSource = gController.ListGlossaryCategoryDefinition();
            mCategoryList.DataBind();
        }

        /// <summary>
        /// Populates the glossary by a letter.
        /// </summary>
        /// <param name="letter">A letter.</param>
        private void PopulateGlossaryByLetter(string letter)
        {
            GlossaryController controller = new GlossaryController();
            if (letter == "All")
                mResultList.DataSource = controller.ListGlossaryByLetter(this.ModuleId,"%");
            else
                mResultList.DataSource = controller.ListGlossaryByLetter(this.ModuleId,letter);
            mResultList.DataBind();
        }

  
        /// <summary>
        ///  Populates the glossary by category.
        /// </summary>
        /// <param name="categoryid">The CategoryDefinitionID</param>
        private void PopulateGlossaryByCat(long categoryid)
        {
            SetIndex(mCategoryDropDownList, categoryid);
            GlossaryController controller = new GlossaryController();
            mResultList.DataSource = controller.ListGlossaryByCategory(this.ModuleId, categoryid);
            mResultList.DataBind();
        }

        /// <summary>
        /// Populates the letters.
        /// </summary>
        private void PopulateLetters()
        {
            mNavLetter.Controls.Clear();
            for (char c = 'A'; c <= 'Z'; c++)
            {
                // new a linkbutton for the letter and add it to the page
                LinkButton letterLinkButton = new LinkButton();
                letterLinkButton.Text = c.ToString();
                letterLinkButton.CommandArgument = c.ToString();

                // set the Command event
                letterLinkButton.Command += new CommandEventHandler(letterLinkButton_Command);
                mNavLetter.Controls.Add(letterLinkButton);

                // new a label to separate the letters
                Label letterlabel = new Label();
                letterlabel.Text = " | ";
                mNavLetter.Controls.Add(letterlabel);
            }
        }


        /// <summary>
        /// Sets the dropDownList's index(set the selected item).
        /// </summary>
        /// <param name="dropDownList"></param>
        /// <param name="value"></param>
        private void SetIndex(DropDownList dropDownList, long value)
        {
            int index = 0;
            for (int i = 0; i < dropDownList.Items.Count; i++)
            {
                if (dropDownList.Items[i].Value == value.ToString())
                {
                    index = i;
                    break;
                }
            }
            dropDownList.SelectedIndex = index;
        }


        /// <summary>
        /// Populates the glossary by a filter string.
        /// </summary>
        /// <param name="filter">The filter string.</param>
        /// <param name="categoryDefinitionId">CategoryDefinitionId</param>
        private void PopulateGlossaryByFilter(string filter, long categoryDefinitionId)
        {
            mFilterTextBox.Text = filter;
            SetIndex(mCategoryDropDownList, categoryDefinitionId);
            GlossaryController controller = new GlossaryController();
            var list = new List<GlossaryInfo>();
            if (categoryDefinitionId == 0)
            {
                list.AddRange(controller.ListGlossaryByFilter(this.ModuleId,filter.Trim()));
            }
            else
            {
                list.AddRange(controller.ListGlossaryByFilterAndCategory(this.ModuleId,filter.Trim(),categoryDefinitionId));
            }
            mResultList.DataSource = list;
            mResultList.DataBind();
        }

        #endregion

        #region Public Methods

        public string GetNavCategoryURL(string category)
        {
            List<string> paramLst = new List<string>();
            paramLst.Add("Category=" + category);
            return Globals.NavigateURL(this.TabId, "", paramLst.ToArray());
        }

        public bool DisplayAudit()
        {
            bool retValue = false;

            if ((string)Settings["auditinfo"] == "Y")
            {
                retValue = true;
            }

            return retValue;
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Page_Load runs when the control is loaded.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            try
            {
                PopulateLetters();
                PopulateTemplate();

                if (!Page.IsPostBack)
                {                                       
                    PopulateCategoryMenu();
                    PopulateCategoryCombo();

                    // get Params and search
                    if (Request.Params["Letter"] != null)
                        PopulateGlossaryByLetter(Request.Params["Letter"].ToString());
                    else if (Request.Params["Filter"] != null && Request.Params["Category"] != null)
                        PopulateGlossaryByFilter(Request.Params["Filter"].ToString(), long.Parse(Request.Params["Category"].ToString()));
                    else if (Request.Params["Category"] != null)
                        //PopulateGlossaryByCat(Request.Params["Category"].ToString());
                        ;
                    else
                        PopulateGlossaryByLetter("A");
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc, true);
            }
        }

        protected void mlnkGlossary_Click(object sender, EventArgs e)
        {
            PopulateGlossaryByFilter(mFilterTextBox.Text, 0);            
        }

        protected void mSearchButton_Click(object sender, System.EventArgs e)
        {
            PopulateGlossaryByFilter(mFilterTextBox.Text, Convert.ToInt64(mCategoryDropDownList.SelectedValue));
        }

        protected void mCategoryList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName.Equals("click"))
            {
                PopulateGlossaryByCat(long.Parse(e.CommandArgument.ToString()));
            }
        }

        private void letterLinkButton_Command(object sender, CommandEventArgs e)
        {
            PopulateGlossaryByLetter(e.CommandArgument.ToString());
        }        

        #endregion

        #region Optional Interfaces


        /// <summary>
        /// Gets the module actions.
        /// </summary>
        /// <value>The module actions.</value>
        public ModuleActionCollection ModuleActions
        {
            get
            {
                ModuleActionCollection Actions = new ModuleActionCollection();
                Actions.Add(this.GetNextActionID(), Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile), ModuleActionType.AddContent, "", "", this.EditUrl(), false, SecurityAccessLevel.Edit, true, false);
                Actions.Add(this.GetNextActionID(), Localization.GetString("ContentOptions.Action", this.LocalResourceFile), ModuleActionType.AddContent, "", "", this.EditUrl("EditCategory"), false, SecurityAccessLevel.Edit, true, false);
                return Actions;
            }
        }

        /// <summary>
        /// Gets the list URL.
        /// </summary>
        /// <returns></returns>
        private string GetListURL()
        {
            DotNetNuke.Entities.Modules.ModuleController controller = new ModuleController();
            return Globals.NavigateURL(controller.GetModuleByDefinition(this.PortalId, "Lists").TabID);
        }

        #endregion
    }
}